package de.gwtprime.server.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;

import de.gwtprime.server.model.Order;
import de.gwtprime.server.model.Transaction;
import de.gwtprime.server.model.User2;
import de.gwtprime.server.sql.helper.HibernateHelper;
import de.gwtprime.server.util.RPCClient;
import edu.emory.mathcs.backport.java.util.Arrays;

/**
 * Show some information about the status of the App
 * (Hibernate connection, RPC connection, etc.)
 * @author jan
 *
 */
public class StatusServlet extends HttpServlet {

	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(StatusServlet.class);
	
	/**
	 * Serial version ID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Servlet pings the database to keep it alive
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		 resp.setContentType("text/html");
		try {
			HibernateHelper.queryDB(new User2(), "from "+User2.class.getSimpleName());
			resp.getWriter().println("Hibernate status: OK");
		} catch (Exception e) {
			resp.getWriter().println("Hibernate status: FAILED");
			resp.getWriter().println(e);
		}
		
		try {
			JSONObject jsonInfo = RPCClient.getInstance().getInfo();
			
			if(jsonInfo.containsKey("version")){
				resp.getWriter().println("<br>RCP status: OK");
			}
			
		} catch (Exception e) {
			resp.getWriter().println("<br>RCP status: FAILED");
			resp.getWriter().println(e);
		}
		
		logger.error("Database was successfully pinged.");
		
		resp.getWriter().println("<h1>Users</h1>");
		printUsers(resp);
		
		resp.getWriter().println("<h1>Deposit / Withdraw</h1>");
		printTransactions(resp);
		
		resp.getWriter().println("<h1>Orders</h1>");
		printOrder(resp);
	}
	
	public void printUsers(HttpServletResponse resp) throws IOException{
		List<User2> users  = HibernateHelper.queryDBForList(new User2(), String.format("from %s", User2.class.getSimpleName()));
		List<Object> title = (Arrays.asList(new Object[]{"ID", "email", "balance", "balance reserved", "activated"}));
		List<List<Object>> list = new ArrayList<>();
		for (User2 user : users) {
			list.add(Arrays.asList(new Object[]{user.getId(), user.getEmail(), user.getBalanceBitcoin(), user.getBalanceBitcoinReserved(), user.isActive()}));
			//resp.getWriter().println(String.format("%s %s", user.getEmail(), user.getBalanceBitcoin()));
		}
		printTable(resp, title, list);
	}
	
	public void printTransactions(HttpServletResponse resp) throws IOException{
		List<Transaction> users  = HibernateHelper.queryDBForList(new Transaction(), String.format("from %s", Transaction.class.getSimpleName()));
		List<Object> title = (Arrays.asList(new Object[]{"ID", "address", "amount", "time", "time received", "txid", "type", "user ID", "confirmed"}));
		List<List<Object>> list = new ArrayList<>();
		for (Transaction user : users) {
			list.add(Arrays.asList(new Object[]{user.getId(), user.getAddress(), user.getAmount(), user.getTime(), user.getTimeReceived(), user.getTransactionId(), user.getType(), user.getUser(), user.isConfirmed()}));
			//resp.getWriter().println(String.format("%s %s", user.getEmail(), user.getBalanceBitcoin()));
		}
		printTable(resp, title, list);
	}
	
	public void printOrder(HttpServletResponse resp) throws IOException{
		List<Order> users  = HibernateHelper.queryDBForList(new Order(), String.format("from %s", Order.class.getSimpleName()));
		List<Object> title = (Arrays.asList(new Object[]{"ID", "amount", "date", "price", "state", "type", "buyer", "seller", "creator", "fee"}));
		List<List<Object>> list = new ArrayList<>();
		for (Order user : users) {
			list.add(Arrays.asList(new Object[]{user.getId(), user.getAmount(), user.getDate(), user.getPrice(), user.getState(), user.getType(), user.getBuyer(), user.getSeller(), user.getUser(), user.getFee()}));
			//resp.getWriter().println(String.format("%s %s", user.getEmail(), user.getBalanceBitcoin()));
		}
		printTable(resp, title, list);
	}
	
	public void printTable(HttpServletResponse resp, List<Object> titles, List<List<Object>> list) throws IOException{
		resp.getWriter().print("<table>");
		
		resp.getWriter().print("<tr>");
		for (Object title : titles) {
			resp.getWriter().print("<td><b>"+title+"</b></td>");
		}
		resp.getWriter().print("</tr>");
		
		for (List<Object> row : list) {
			resp.getWriter().print("<tr>");
			
			for(Object entry : row){
				resp.getWriter().print("<td>"+entry +"</td>");
			}
			resp.getWriter().print("</tr>");
		}
		resp.getWriter().print("</table>");
		
	}
	
	
}
